﻿using System;
using System.ComponentModel.Design;
using System.Diagnostics;

namespace SedionFormDesigner.Designer
{
    /// <summary>
    ///  设计器执行过程中的事务管理器
    /// </summary>
    public class SedionDesignerTransaction : DesignerTransaction
    {
        private SedionDesignerHost host;
        public SedionDesignerTransaction(SedionDesignerHost host, String description)
            : base(description)
        {
            this.host = host;
            // 在堆栈中添加事务的文字描述
            host.TransactionDescriptions.Push(description);

            // 如果是第一个事务,那么触发opening,opened事件
            if (host.TransactionCount++ == 0)
            {
                host.OnTransactionOpening(EventArgs.Empty);
                host.OnTransactionOpened(EventArgs.Empty);
            }
        }

        protected override void OnCancel()
        {
            if (host != null)
            {
                Debug.Assert(host.TransactionDescriptions != null, "End batch operation with no description");
                String description = (String)host.TransactionDescriptions.Pop();

                // 如果最后个事务关闭了,触发closing/closed事件
                if (--host.TransactionCount == 0)
                {
                    DesignerTransactionCloseEventArgs dte = new DesignerTransactionCloseEventArgs(false);
                    host.OnTransactionClosing(dte);
                    host.OnTransactionClosed(dte);
                }
                host = null;
            }
        }

        protected override void OnCommit()
        {
            if (host != null)
            {
                Debug.Assert(host.TransactionDescriptions != null, "End batch operation wirh no description?");
                String descript = (String)host.TransactionDescriptions.Pop();

                // 如果最后个事务关闭了,触发closing/closed事件
                if (--host.TransactionCount == 0)
                {
                    DesignerTransactionCloseEventArgs dte = new DesignerTransactionCloseEventArgs(true);
                    host.OnTransactionClosing(dte);
                    host.OnTransactionClosed(dte);
                }
                host = null;
            }
        }
    }
}
